import { DataSource } from 'typeorm';
import {
  Permission,
  PermissionAction,
} from '@src/permission/entity/permission.entity';

function buildPermissions() {
  const resources = ['user', 'role'];
  const actions = [
    PermissionAction.CREATE,
    PermissionAction.READ,
    PermissionAction.UPDATE,
    PermissionAction.DELETE,
  ];

  const result: Partial<Permission>[] = [];

  for (const resource of resources) {
    for (const action of actions) {
      const code = `${resource}:${action}`;
      result.push({
        resource,
        action,
        code,
        description: `允许 ${action} 操作 ${resource}`,
      });
    }
  }

  return result;
}

export async function seedPermissions(dataSource: DataSource): Promise<void> {
  const repo = dataSource.getRepository(Permission);
  const permissions = buildPermissions();

  await repo.upsert(permissions, ['code']);
}
